package hydrap2p.modulemanager;

import hydrap2p.ServiceLocation;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.thrift.TException;

public class ModuleManagerServiceListener implements hydrap2p.servicemanager.ServiceListener.Iface {

	private final ModuleController controller;
	private final Map<String, Runnable> hooks;
	private final Map<String, Runnable> permhooks;
	
	
	public ModuleManagerServiceListener(ModuleController controller)
	{
		this.controller=controller;
		this.hooks=new TreeMap<String, Runnable>();
		this.permhooks=new TreeMap<String, Runnable>();
	}
	
	
	@Override
	public void ping() throws TException {
	}

	@Override
	public List<String> supportedInterfaces() throws TException {
		return Arrays.asList("Service", "ServiceListener");
	}

	@Override
	public void newService(String arg0, ServiceLocation arg1) throws TException {
		Runnable hook=null;
		Runnable permhook=null;
		System.out.println("New service registered "+arg0+" at "+arg1);
		controller.serviceStarted(arg0, arg1);
		synchronized(hooks)
		{
			if (hooks.containsKey(arg0))
			{
				hook=hooks.remove(arg0);
			}
			if (permhooks.containsKey(arg0))
			{
				permhook=permhooks.get(arg0);
			}
		}
		if (permhook!=null)
		{
			permhook.run();
		}
		if (hook!=null)
		{
			hook.run();
		}
	}

	@Override
	public void delService(String arg0) throws TException {
		controller.serviceStopped(arg0);
	}
	
	public void registerHook(String name, Runnable hook, boolean permanent) {
		synchronized(hooks)
		{
			if (permanent)
				permhooks.put(name,hook);
			else
				hooks.put(name,hook);
		}
	}
	public void removeHook(String name, boolean permanent) {
		synchronized(hooks)
		{
			if (permanent)
				permhooks.remove(name);
			else
				hooks.remove(name);
		}		
	}

}
